package com.behelpful.common.data.typehandler;

import cn.hutool.core.util.StrUtil;
import com.behelpful.common.core.utils.ICollUtil;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

/**
 * 自定义字符串集合转字符串
 *
 * @author Alay
 * @date 2021-09-03 15:00
 */
public abstract class Str2CollectionTypeHandler<T extends Collection<String>> implements TypeHandler<T> {

    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, T list, JdbcType jdbcType) throws SQLException {
        if (null == list || list.isEmpty()) {
            preparedStatement.setString(index, null);
            return;
        }
        String coll2Str = this.parseStr(list, StrUtil.COMMA);
        preparedStatement.setString(index, coll2Str);
    }

    @Override
    public T getResult(ResultSet resultSet, String columnName) throws SQLException {
        String str = resultSet.getString(columnName);
        if (null == str) {
            return null;
        }
        T asColl = this.toCollection(str.split(StrUtil.COMMA));
        return asColl;
    }

    @Override
    public T getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String str = resultSet.getString(columnIndex);
        if (null == str) {
            return null;
        }
        T asColl = this.toCollection(str.split(StrUtil.COMMA));
        return asColl;
    }

    @Override
    public T getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String str = callableStatement.getString(columnIndex);
        if (null == str) {
            return null;
        }
        T asColl = this.toCollection(str.split(StrUtil.COMMA));
        return asColl;
    }

    /**
     * 字符串转集合类型函数定义
     *
     * @param array
     * @return
     */
    public abstract T toCollection(String... array);

    /**
     * 集合转 String
     *
     * @param collection 目标集合
     * @param regex      分隔符
     * @return
     */
    public  String parseStr(Collection<?> collection, String regex){
        return ICollUtil.coll2Str(collection, regex);
    }

}
